part of "../basic.dart";

extension Cut on String {
  /// 当长度超过一定值时，会将后面的部分剪掉，并添加...
  /// 比如说：太长的标题是这样...
  String truncate(int maxLength) {
    int length = 0;
    int runeCount = 0;

    for (var rune in runes) {
      if (rune < 128) {
        // ASCII字符
        length += 1;
      } else {
        // 非ASCII字符
        length += 2;
      }

      if (length > maxLength * 2) {
        break;
      }

      runeCount += 1;
    }

    return (runeCount < this.length) ? '${substring(0, runeCount)}...' : this;
  }

  /// 去除空行
  String removeBlankLines() => split('\n') // 按行分割
      .where((line) => line.trim().isNotEmpty) // 过滤掉空行
      .join('\n'); // 重新组合
}

const String _numbers = "0123456789";

extension TextTest on String {
  /// 检查一个字符串是不是纯数字
  bool get isPureNumber {
    for (int i = 0; i < length; i++) {
      if (!_numbers.contains(this[i])) return false;
    }
    return true;
  }

  /// 检查字符串中中文的数量
  int get chineseCount {
    int count = 0;
    for (String i in split("")) {
      RegExp chinese = RegExp('[\u4e00-\u9fff]+');
      if (i.contains(chinese)) count++;
    }
    return count;
  }
}
